<?php

namespace Apps\Manage\Controllers;

use Apps\Common\Enum\SearchDataType;
use Apps\Common\Libs\BeautyParlorSyncLocation;
use Apps\Common\Libs\SearchASync;
use Apps\Common\Libs\UploadPic;
use Apps\Common\Models\BeautyParlor;
use Apps\Common\Models\BeautyParlorPhotos;
use Apps\Common\Models\BeautyParlorTag;
use Apps\Common\Models\OmBanner;
use Apps\Common\Models\SysAreaZipDistrictPhonecode;
use Apps\Common\Models\Branch;
use Phalcon\Db\RawValue;
use Phalcon\Mvc\View;
use PhalconPlus\Common\ResponseResult;
use PhalconPlus\Common\ResponseResultStatus;
use Apps\Common\Models\Agents;
use Apps\Common\Models\BeautyParlorTagInfo;
use Apps\Common\Models\BeautyParlorAttr;
use Apps\Common\Models\CosPointBp;
use Apps\Common\Models\SysOpenCity;
use Apps\Common\Libs\SmaUtil;
use Phalcon\Exception;

/**
 * 美容院管理
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class BpController extends BpBaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->setMainNav('bp');
    }

    public function indexAction()
    {
        $this->response->redirect('bp/list');
    }
    /**
     * 开通的城市
     * @return \Phalcon\Mvc\Model\Criteria
     */
    private function openCityList()
    {
    	return SysOpenCity::find();
    }
    /**
     * 美容院列表
     */
    public function listAction()
    {
        $this->setLeftNav('bp_list');
        $req = $this->request;
        $page = intval($req->getQuery('page', null, 1));
        $page = $page > 0 ? $page : 1;
        $limit = $this->pageNavLimit;
        $offset = $limit * ($page - 1);

        $filterProvince = $req->getQuery('filterProvince', null, '');
        $filterCity = $req->getQuery('filterCity', null, '');
        $filterDistrict = intval($req->getQuery('filterDistrict', null, -10000));

        $filterState = intval($req->getQuery('filterState', null, -10000));
        $filterSell = intval($req->getQuery('filterSell', null, -10000));
        $filterMedal = intval($req->getQuery('filterMedal', null, -10000));
		
        $filterName = $req->getQuery('filterName', null, '');
		
        $columns = [
            'bp_id',
            'bp_name',
            'bp_cover',
            'bp_address',
            'bp_district',
            'FULL_NAME district',
            'bp_coordinate',
            'bp_tel',
            'bp_intro',
            'bp_state',
            'bp_is_sell',
            'bp_medal',
            'bp_addtime'
        ];
        $where = [];
        $bind = [];
        $medal = [];
        if(!!$filterName) {
            $where[] = 'bp_name LIKE :fname:';
            $bind['fname'] = '%' . $filterName . '%';
        }
        if($filterState > -10000) {
            $where[] = 'bp_state = :state:';
            $bind['state'] = $filterState;
        }
        if($filterSell > -10000) {
            $where[] = 'bp_is_sell = :sell:';
            $bind['sell'] = $filterSell;
        }
        // 勋章
        switch($filterMedal) {
            case 1:
                $medal = ['10', '11'];
                break;
            case 2:
                $medal = ['01', '11'];
                break;
            case 3:
                $where[] = 'bp_medal = :medal:';
                $bind['medal'] = '11';
        }
        $districts = [];
        // 地区
        if($filterDistrict > -10000) {
            $where[] = 'bp_district = :district:';
            $bind['district'] = $filterDistrict;
        } elseif(!empty($filterCity)) {
            // 获取所有城市的下级区县值
            $dids = SysAreaZipDistrictPhonecode::query()
                ->columns(['K_ID id'])
                ->where('P_NM = :province: AND C_NM = :city:', ['province' => $filterProvince, 'city' => $filterCity])
                ->execute();
            foreach($dids as $d) {
                $districts[] = $d->id;
            }
        } elseif(!empty($filterProvince)) {
            // 获取所有城市的下级区县值
            $dids = SysAreaZipDistrictPhonecode::query()
                ->columns(['K_ID id'])
                ->where('P_NM = :p:', ['p' => $filterProvince])
                ->execute();
            foreach($dids as $d) {
                $districts[] = $d->id;
            }
        }
        if(count($medal) > 0) {
            $where[] = 'bp_medal IN(' . implode(', ', $medal) . ')';
        }
        if(count($districts) > 0) {
            $where[] = 'bp_district IN(' . implode(', ', $districts) . ')';
        }

        $whereStr = implode(' AND ', $where);

        $query = BeautyParlor::query()
            ->columns($columns)
            ->leftJoin('Apps\Common\Models\SysAreaZipDistrictPhonecode', 'K_ID=bp_district', 'area');

        if(!empty($whereStr)) {
            $query = $query->where($whereStr);
        }

        if(count($bind) > 0) {
            $query = $query->bind($bind);
        }

        $bpList = $query
            ->orderBy('bp_id DESC')
            ->limit($limit, $offset)
            ->execute();
        // 总数
        $total = BeautyParlor::count([
            'conditions' => $whereStr,
            'bind' => $bind,
        ]);

        $this->view->setVar('filterProvince', $filterProvince);
        $this->view->setVar('filterCity', $filterCity);
        $this->view->setVar('filterDistrict', $filterDistrict);

        $this->view->setVar('filterState', $filterState);
        $this->view->setVar('filterName', $filterName);
        $this->view->setVar('filterSell', $filterSell);
        $this->view->setVar('filterMedal', $filterMedal);
		
        $this->view->setVar('shopState' , $shopState);
        
        $this->view->setVar('total', $total);
        $this->view->setVar('page', $page);
        $this->view->setVar('limit', $limit);

        $this->view->setVar('bpList', $bpList);

        $this->view->setVar('bpStateList', \Apps\Common\Enum\BeautyParlor::valuesExplain());
    }

    /**
     * 添加新的美容院
     */
public function addAction()
    {
        $this->setLeftNav('bp_add');
        $req = $this->request;
        if(!$req->isPost()) {
            $bp_id = $req->getQuery('bp_id',null,0);
            $branch_id = $req->getQuery("branch_id");
            $echo = function($msg, $state=false){
                echo '<script type="text/javascript">';
                echo 'parent.formResult("' . $msg . '", ' . ($state ? 1 : 0) . ')';
                echo '</script>';
            };
            if ($bp_id==0){
                $this->view->setVar("branch_id",$req->getQuery("branch_id"));
                return;
            }
            else{//如果bp_id不为空  绑定 branchid 和 美容院id
                try {
                    $this->db->begin();
                    $bpinfo = BeautyParlor::findFirst("bp_id = $bp_id");
                    if ($bpinfo){
                        $rs = $bpinfo->update(['branch_id'=>$branch_id]);
                        if(!$rs){
                            $echo('修改失败');
                            return;
                        }
            
                        $branch=Branch::findFirst("shop_id = $branch_id");
                        $flg = $branch->update(["status"=>200]);
                        //$branch->status=200;
                        //$flg=$branch->save();
                        
                        //修改sma端状态
                        $smautil = new SmaUtil();
                        $rs = $smautil->updateOnline($branch_id);
                        
                        $this->db->commit();
                        $this->response->redirect('bp/apply');
                    }
                }
                catch (\Exception $e){
                    $this->db->rollback();
                }
            }
        }
        
        // 输出js
        $echo = function($msg, $state=false){
            echo '<script type="text/javascript">';
            echo 'parent.formResult("' . $msg . '", ' . ($state ? 1 : 0) . ')';
            echo '</script>';
        };
            
        $this->view->disable();
        $name = $req->getPost('bp_name');
        $district = intval($req->getPost('bp_district', null, 0));
        $address = $req->getPost('bp_address');
        $coordinate = $req->getPost('bp_coordinate');
        $tel = $req->getPost('bp_tel');
        $isSell = intval($req->getPost('bp_is_sell', null, 0));
        $medalRefund = intval($req->getPost('bp_medal_refund', null, 0));
        $medalVerify = intval($req->getPost('bp_medal_verify', null, 0));
        $tags = $req->getPost('bp_tags');
        $branch_id=$req->getPost("branch");//绑定分店ID
        
        $ownerMobile = $req->getPost('bp_owner_mobile');
        $intro = $req->getPost('bp_intro');
        ////////////////////////////////////2.0新加参数////2.0新加参数///////2.0新加参数///////2.0新加参数///////////////////////////////
        $low_price=$req->getPost("low_price",null,0);//起步价                                                                 
        $open_year=$req->getPost("open_year",null,0);//开业年限                                                                   
        $shop_area=$req->getPost("shop_area",null,0);//店铺面积                                                            
        $service_num=$req->getPost("service_num",null,0);//服务项目数量                                                   
        $op_cl_time=$req->getPost("time",null,'');//营业时间     
		$facilities=$req->getPost("facilities",null,'');//设备设施                                                                     
        if($op_cl_time!=''){                                                                                                                        
        	$op_cl_time_arr=explode("至",$op_cl_time);                                                                    
        	$open_time=trim($op_cl_time_arr[0]);                                                                      
        	$close_time=trim($op_cl_time_arr[1]);                                                                    
        }else{                                                                                                     
        	$open_time='';
        	$close_time='';
        }
        /* if($low_price < 0  || $open_year < 0 || $shop_area < 0 || $service_num < 0){
        	$echo('数据不能为空！');
        	return;
        } */
        if($facilities!=''){
	        try {
	        	$facilities_json=json_encode($facilities);
	        }catch (\Exception $e){
	        	$echo('数据错误！');
	        }
        }else{
        	$facilities_json=null;
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        // 判断空数据
        if(empty($name) || $district <= 0 || empty($address) || empty($coordinate) || empty($tel) || empty($tags) || empty($intro) || empty($ownerMobile)) {
            $echo('数据不能为空！');
            return;
        }
       
        try {
        	$this->db->begin();
        	// 保存封面
        	$uploadFile = new UploadPic();
        	$uploadFile->request = $req;
        	$cover = $uploadFile->beautyParlorCover();
        	if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
        		 
        		if($_FILES['bp_cover']['error'] == 1) {
        			$echo('封面大小超过了2M！');
        			//$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了1M！');
        		} else {
        			//$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件处理异常！');
        			$echo('封面必须上传！');
        		}
        		return;
        	}
        	
        	//分店信息
        	//$info=Branch::query()->where("branch_id = $branch_id")->execute()->toArray();
        	if($branch_id!=''){
        		$info=Branch::findFirst("shop_id = $branch_id")->toArray();
        	}
        	
        	$bpCover = $cover[0];
        	// 保存基础数据
        	$coordinate = str_replace(',', ' ', $coordinate);
        	$bp = new BeautyParlor();
        	$bp->bp_name = $name;
        	$bp->bp_cover = $bpCover;
        	$bp->bp_address = $address;
        	$bp->bp_district = $district;
        	$bp->bp_coordinate = new RawValue("GeomFromText('POINT($coordinate)')");
        	$bp->bp_tel = $tel;
        	$bp->bp_owner_mobile = $ownerMobile;
        	$bp->bp_intro = $intro;
        	$bp->bp_is_sell = $isSell;
        	$bp->bp_medal = strval($medalRefund) . strval($medalVerify);
        	$bp->branch_id=$branch_id;
        	$bp->start_time=date('Y-m-d H:i:s',time());
        	
        	if($branch_id != ''){
        		$bp->long_time=$info->long_time;
        		$bp->start_time=$info->start_time;
        		$bp->end_time=$info->end_time;
        	}
        	$rs_bp = $bp -> save();
        	if($rs_bp == false){
        		$echo('保存基础数据异常！');
        		$this->databaseErrorLog($bp);
        		return;
        	}
        	/* if($bp->save() == false) {
        	 $echo('保存基础数据异常！');
        	 $this->databaseErrorLog($bp);
        	 return;
        	 } */
        	$bpId = $bp->bp_id;
        	/*保存美容院相关数据  */
        	$bp_attr=new BeautyParlorAttr();
        	$bp_attr->beauty_parlor_id=$bpId;
        	$bp_attr->close_time=$close_time;
        	$bp_attr->open_time=$open_time;
        	$bp_attr->low_price=$low_price;
        	$bp_attr->open_year=$open_year;
        	$bp_attr->facilities=$facilities_json;
        	$bp_attr->service_num=$service_num;
        	$bp_attr->shop_area=$shop_area;
        	if(!$bp_attr->save()){
        		$echo('添加失败！');
        	}
        	// 保存标签
        	$tagsArr = explode(',', $tags);
        	 foreach($tagsArr as $tag) {
	        	 $tagDb = new BeautyParlorTag();
	        	 $tagDb->bp_id = $bpId;
	        	 $tagDb->tag_id = $tag;
	        	 if($tagDb->save() == false) {
	        	 	$this->databaseErrorLog($tagDb);
	        	 }
        	 }
        	// 保存轮播图片
        	// 轮播图片
        	$pics = $uploadFile->beautyParlorPics();
        	$error = $_FILES['bp_photos']['error'];
        	
        	if(!empty($pics)){
        		foreach ($error as $k => $v){
        			if($v == 1){
        				$echo('轮播图片大小超过了2M！');
        				return ;
        			}
        		}
        		foreach($pics as $pic) {
        			$picDb = new BeautyParlorPhotos();
        			$picDb->beauty_parlor_id = $bpId;
        			$picDb->photo_url = $pic;
        			$rs_pic = $picDb -> save();
        			if($rs_pic == false){
        				$this->databaseErrorLog($picDb);
        			}
        			/* if($picDb->save() == false) {
        			 $this->databaseErrorLog($picDb);
        			 } */
        		}
        	}else{
        		$echo('封面大小超过了2M！');
        		return ;
        	}
        	
        	 
        	
        	/* if($pics == false || !is_array($pics) || count($pics) == 0 || $pics[0] == false) {
        	 if($_FILES['bp_photos']['error'] == 1) {
        	 $echo('封面大小超过了2M！');
        	 //$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了1M！');
        	 } else {
        	 //$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件处理异常！');
        	 $echo('封面必须上传！');
        	 }
        	 return;
        	 } */
        	/* foreach($pics as $pic) {
        	 $picDb = new BeautyParlorPhotos();
        	 var_dump($pic);
        	 exit;
        	 $picDb->beauty_parlor_id = $bpId;
        	 $picDb->photo_url = $pic;
        	 if($picDb->save() == false) {
        	 $this->databaseErrorLog($picDb);
        	 }
        	 } */
        	if($branch_id != ''){//修改分店状态
        		$branch=Branch::findFirst("shop_id = $branch_id");
        		$branch->status=200;
        		$flg=$branch->save();
        		
        		//修改sma端状态
        		$smautil = new SmaUtil();
        		$rs = $smautil->updateOnline($branch_id);
        	}
        	SearchASync::Instance()->noticeSync($bpId, SearchDataType::BeautyParlors);       	
        	$this->db->commit();
        	$echo($bpId, true);
        } catch (\Exception $e) {
        	$this->db->rollback();
        }
           
    }

    /**
     * 设置美容院状态
     * @return $this|ResponseResult
     */
    public function setStateAction()
    {
        $req = $this->request;
        if($req->isPost()) {
            $id = intval($req->getPost('id', null, 0));
            $state = intval($req->getPost('state', null, -10000));
            if(!in_array($state, [-1, 0, 1])) {
                return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
            }
            if($state == -1)
            {
                // 查询美容院是否在首页推荐！
                $bannerBp = OmBanner::query()
                    ->columns('banner_data')
                    ->where('city_id > 0 AND banner_name = :key:', ['key' => 'index_bp'])
                    ->execute();
                foreach ($bannerBp as $bb)
                {
                    if (intval($bb->banner_data) == $id)
                    {
                        return (new ResponseResult())->sendError(ResponseResultStatus::BUSINESS, '此美容院在首页推荐，不能删除！');
                    }
                }
            }
            $info = BeautyParlor::findFirst('bp_id=' . $id);
            if($info) {
                $info->update(['bp_state' => $state]);
            }
//             $is_product=$this->di->get('appConfig')->is_product;
//             if($is_product){
            $syncMap = new BeautyParlorSyncLocation();///上传数据到高德地图
            if($state == 1) {
                $syncMap->sync($id);
            } else {
                $syncMap->delete($id);
            }
//             }
            SearchASync::Instance()->noticeSync($id, SearchDataType::BeautyParlors);
            return (new ResponseResult())->sendResult('ok');
        } else {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '请求异常');
        }
    }

    /**
     * 修改
     */
    public function updateAction()
    {
        $this->setLeftNav('bp_update');
        $req = $this->request;
        if(!$req->isPost()) {
            $id = intval($req->getQuery('id', null, 0));
            if ($id < 1) {
                $this->view->disable();
                echo '参数异常！';
                return;
            }
            // 获取美容院信息
            $info = BeautyParlor::query()
                ->columns([
                    'bp_id',
                    'bp_name',
                    'bp_cover',
                    'bp_address',
                    'bp_district',
                    'bp_coordinate',
                    'bp_tel',
                    'bp_intro',
                    'bp_state',
                    'bp_is_sell',
                    'bp_medal',
                    'bp_owner_mobile',
                    'bp_addtime',
                    'X(bp_coordinate) latitude',
                    'Y(bp_coordinate) longitude',
                ])
                ->where('bp_id=:id:')
                ->bind(['id' => $id])
                ->execute()->getFirst();
            if (!$info) {
                $this->view->disable();
                echo '美容院不存在！';
                return;
            }
            //美容院图片
            $pics = BeautyParlorPhotos::query()
                ->columns(['photo_url', 'photo_id'])
                ->where('photo_state>0 and beauty_parlor_id=:bid:')
                ->bind(['bid' => $id])
                ->execute();
            //美容院标签
            $tagList = $this->getBeautyParlorTags($id);
            $tagListDataIds = [];
            $tagListDataTitles = [];
            foreach ($tagList as $tag) {
                $tagListDataIds[] = $tag->tag_id;
                $tagListDataTitles[] = $tag->tag_title;
            }
            $tagListData = [
                implode(',', $tagListDataIds),
                implode(',', $tagListDataTitles),
            ];
            //美容院2.0新增美容院属性
            $bp_attr_model=BeautyParlorAttr::findFirst("beauty_parlor_id = $id");
            if($bp_attr_model){
            	$bp_attr=$bp_attr_model->toArray();
            }
            $facilitiesArr=json_decode($bp_attr['facilities']);
            
            $this->view->setVar('facilitiesArr',$facilitiesArr);
            $this->view->setVar('bp_attr',$bp_attr);
            $this->view->setVar('bpInfo', $info);
            $this->view->setVar('tagList', $tagListData);
            $this->view->setVar('picList', $pics);
            $this->view->setVar('bpArea', $this->getDistrictInfo($info->bp_district));
            $this->view->setVar('id', $id);
        } else {
            //更新美容院信息
            return $this->updateSave();
        }
    }

    /**
     * 更新数据
     * @return ResponseResult
     */
    private function updateSave()
    {
        $req = $this->request;
        $response = new ResponseResult();
        $response->callback = $req->getPost('callback', null, 'parent.setFormResult');
        $response->callbackJavascriptTag = true;

        $id = intval($req->getPost('bp_id'));
        if($id < 1) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
            return $response;
        }
        $name = $req->getPost('bp_name');
        $district = intval($req->getPost('bp_district', null, 0));
        $address = $req->getPost('bp_address');
        $coordinate = $req->getPost('bp_coordinate');
        $tel = $req->getPost('bp_tel');
        $isSell = intval($req->getPost('bp_is_sell', null, 0));
        $medalRefund = intval($req->getPost('bp_medal_refund', null, 0));
        $medalVerify = intval($req->getPost('bp_medal_verify', null, 0));
        $tags = $req->getPost('bp_tags');
        $ownerMobile = $req->getPost('bp_owner_mobile');
        $intro = $req->getPost('bp_intro');
        ////////////////////////////////////2.0新加参数////2.0新加参数///////2.0新加参数///////2.0新加参数///////////////////////////////
        $low_price=$req->getPost("low_price",null,0);//起步价
        $open_year=$req->getPost("open_year",null,0);//开业年限
        $shop_area=$req->getPost("shop_area",null,0);//店铺面积
        $service_num=$req->getPost("service_num",null,0);//服务项目数量
        $op_cl_time=$req->getPost("time",null,'');//营业时间
        $facilities=$req->getPost("facilities",null,'');//设备设施
        if($op_cl_time!=''){
        	$op_cl_time_arr=explode("至",$op_cl_time);
        	$open_time=trim($op_cl_time_arr[0]);
        	$close_time=trim($op_cl_time_arr[1]);
        }else{
        	$open_time='';
        	$close_time='';
        }
        if($low_price < 0  || $open_year < 0 || $shop_area < 0 || $service_num < 0){
        	$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '数据不能为空！');
        	return;
        }
        if($facilities!=''){
        	try {
        		$facilities_json=json_encode($facilities);
        	}catch (\Exception $e){
        		$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '数据错误！');
        		return;
        	}
        }else{
        	$facilities_json=null;
        }
        
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        // 判断空数据
        if(empty($name) || $district <= 0 || empty($address) || empty($coordinate) || empty($tel) || empty($tags) || empty($intro) || empty($ownerMobile)) {
            $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
            return $response;
        }
        // 保存封面
        $uploadFile = new UploadPic();
        $uploadFile->request = $req;
        $cover = $uploadFile->beautyParlorCover();
        if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
            $bpCover = null;
        } else {
            $bpCover = $cover[0];
        }

        // 保存基础数据
        $coordinate = str_replace(',', ' ', $coordinate);
        $bp = BeautyParlor::findFirst('bp_id = ' . $id);
        $data = [];
        if($bp->bp_name != $name) {
            $data['bp_name'] = $name;
        }
        if(!!$bpCover) {
            $data['bp_cover'] = $bpCover;
        }
        if($bp->bp_address != $address) {
            $data['bp_address'] = $address;
        }
        if($bp->bp_district != $district) {
            $data['bp_district'] = $district;
        }
        $data['bp_coordinate'] = new RawValue("GeomFromText('POINT($coordinate)')");
        if($bp->bp_tel != $tel) {
            $data['bp_tel'] = $tel;
        }
        if($bp->bp_owner_mobile != $ownerMobile) {
            $data['bp_owner_mobile'] = $ownerMobile;
        }
        if($bp->bp_intro != $intro) {
            $data['bp_intro'] = $intro;
        }
        if($bp->bp_is_sell != $isSell) {
            $data['bp_is_sell'] = $isSell;
        }
        $data['bp_medal'] = strval($medalRefund) . strval($medalVerify);
        $bp->update($data);
        /*保存美容院相关数据  */
        $bp_attr=BeautyParlorAttr::findFirst("beauty_parlor_id = $id");
        if(!$bp_attr){
        	/* $response->sendError(ResponseResultStatus::ERROR, '修改失败！');
        	return $response; */
        	$bp_attr=new BeautyParlorAttr();
        }
        $bp_attr->beauty_parlor_id=$id;
        $bp_attr->close_time=$close_time;
        $bp_attr->open_time=$open_time;
        $bp_attr->low_price=$low_price;
        $bp_attr->open_year=$open_year;
        $bp_attr->facilities=$facilities_json;
        $bp_attr->service_num=$service_num;
        $bp_attr->shop_area=$shop_area;                                                                                                                                                                         
        if(!$bp_attr->save()){
        	$response->sendError(ResponseResultStatus::ERROR, '添加失败！');
        }
        //处理标签
        $tagsArr = explode(',', $tags);
       	foreach($tagsArr as $tag) {
            $tagDb = BeautyParlorTag::query()
                ->columns('bp_tag_id, bp_id, tag_id')
                ->where('bp_id = :bid: AND tag_id = :tid:')
                ->bind(['bid'=>$id, 'tid'=>$tag])
                ->execute()->getFirst();
            if(!$tagDb) {
                $tagDb = new BeautyParlorTag();
                $tagDb->bp_id = $id;
                $tagDb->tag_id = $tag;
                if ($tagDb->save() == false) {
                    $this->databaseErrorLog($tagDb);
                }
            }
        }
        // 获取所有的标签
        $tagList = BeautyParlorTag::query()
            ->where('bp_id = :bid:')
            ->bind(['bid'=>$id])
            ->execute();
        foreach($tagList as $t) {
            if(in_array(strval($t->tag_id), $tagsArr) == false) {
                $t->delete();
            }
        }
        // 保存轮播图片
        // 轮播图片
        $pics = $uploadFile->beautyParlorPics();
        if($pics) {
            foreach ($pics as $pic) {
                $picDb = new BeautyParlorPhotos();
                $picDb->beauty_parlor_id = $id;
                $picDb->photo_url = $pic;
                if ($picDb->save() == false) {
                    $this->databaseErrorLog($picDb);
                }
            }
        }
        SearchASync::Instance()->noticeSync($id, SearchDataType::BeautyParlors);
        $response->sendResult('ok');
        return $response;
    }

    /**
     * 删除美容院图片
     * @date: 2016年1月19日 
     * @author: chenxiaolin
     */
    public function deletePhotoAction()
    {
        $req = $this->request;
        if(!$req->isPost()) {
            return (new ResponseResult())->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, 'request method error.');
        }
        $bpId = intval($req->getPost('bid', null, 0));
        $picId = intval($req->getPost('pid', null, 0));
        $picDb = BeautyParlorPhotos::findFirst('photo_id = ' . $picId . ' AND beauty_parlor_id = ' . $bpId);
        if($picDb) {
            $picDb->update(['photo_state'=>-1]);
        }
        return (new ResponseResult())->sendResult('ok');
    }
    
    /*申请开通美容院列表 1.0 */
    public function applyAction(){
    	$this->setLeftNav("apply");
    	$agents_list=Branch::query()->columns(['agent_id,agent_name'])->where("agent_id is not null AND agent_name is not null group by agent_id")->execute()->toArray();//代理商列表
    	$req = $this->request;
    	$page = intval($req->getQuery('page', null, 1));
    	$page = $page > 0 ? $page : 1;
    	$limit = $this->pageNavLimit;
    	$offset = $limit * ($page - 1);
    	if($req->getQuery("agent_id")!=''){
    		$wherearr[]="agent_id=".$req->getQuery("agent_id");
    		$this->view->setVar("agent_id",$req->getQuery("agent_id"));
    	}else{
    		$wherearr[]="agent_id!=''";
    	}
    	$wherearr[]="status=100";
    	$where=implode(" and ",$wherearr);
    	
    	$query=Branch::query();
    	$total=Branch::count(['conditions'=>$where]);
		$list = $query
			->where($where)
            ->orderBy('branch_id DESC')
            ->limit($limit, $offset)
            ->execute()
			->toArray();
// 		foreach ($list as $k=>$v){
// 			$tmp=Agents::query()->where("agent_id = ".$list[$k]['agent_id'])->execute()->toArray();
// 			$list[$k]['agent_name']=$tmp[0]['agent_name'];
// 		}
    	$this->view->setVar("total",$total);
    	$this->view->setVar("limit",$limit);
    	$this->view->setVar("page",$page);
    	$this->view->setVar("list",$list);
    	$this->view->setVar("agents_list",$agents_list);
    	$this->view -> pick("bp/apply");
    }
	
    /**
     * 首页推荐美容院列表
     * @date: 2016-1-8 
     * @author: futao
     */
    public function bannerBpAction()
    {
    	//error_reporting(E_ALL);
    	$this->setLeftNav('bannerbp');
    	$key = 'index_bp';
    	$req = $this->request;
    	if(!$req->isPost()) {
    		$filterCity = intval($req->getQuery('City',null, 0));
    		$this->view->setVar('openCity', $this->openCityList());
    		$this->view->setVar('filterCity', $filterCity);
    		$page = intval($req->getQuery('page', null, 1));
    		$page = $page > 0 ? $page : 1;
    		$limit = $this->pageNavLimit;
    		$offset = $limit * ($page - 1);
    		$count=CosPointBp::count(['conditions'=>"addr = $filterCity"]);
    		$list=CosPointBp::query()
    		->where("addr = '$filterCity'")
    		->limit($limit, $offset)
    		->execute()
    		->toArray();
    		foreach ($list as $k=>$v){
    			$tmp=SysOpenCity::findFirst("city_id = ".$list[$k]['addr']);
    			if($tmp){
    				$tmp = $tmp->toArray();
    			}
    			$list[$k]['city_name']=$tmp['city_name'];
    			$list[$k]['img_url']="http://img.meelier.com/".$list[$k]['img_url'];
    		}
    		$this->view->setVar("total",$count);
    		$this->view->setVar("limit",$limit);
    		$this->view->setVar("page",$page);
    		$this->view->setVar("list",$list);
    		
    		$this->view->setVar('filterCity', $filterCity);
    		$this -> view -> pick('bp/bannerBp');
    		return;
    	} else {//1.0版本代码，2.0没使用
    		$response = new ResponseResult();
    		$bpId = intval($req->getPost('bpid', null, 0));
    		$city = intval($req->getPost('city', null, 0));
    		//判断参数是否合法
    		if($bpId < 1 || $city < 1) {
    			return $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常');
    		}
    		// 查询美容院是否存在
    		if(BeautyParlor::count('bp_id = ' . $bpId) == 0) {
    			return $response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '美容院不存在！');
    		}
    		
    		$bannerData = OmBanner::query()
    		->where('city_id = :cid: AND banner_name = :key:', ['cid' => $city, 'key' => $key])
    		->execute()
    		->getFirst();
    		if($bannerData) {
    			$bannerData->update(['banner_data'=>$bpId, 'banner_update_time' => new RawValue('NOW()')]);
    			$response->sendResult($bannerData->banner_id);
    		} else {
    			$bannerData = new OmBanner();
    			$bannerData->city_id = $city;
    			$bannerData->banner_name = $key;
    			$bannerData->banner_data = $bpId;
    			if($bannerData->save() == false) {
    				$this->databaseErrorLog($bannerData);
    				$response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常');
    			} else {
    				$response->sendResult($bannerData->banner_id);
    			}
    		}
    		return $response;
    	}
    }
    /**
     * 添加首页推荐美容院
     * @date: 2016-1-8 
     * @author: futao
     */
    public function bannerBpAddAction()
    {
    	 
    	$this->setLeftNav('bannerbp');
    	$req = $this -> request;
    	if(!$req->isPost()) {
    		$this->view->setVar('bp_id',$req->getQuery('id',null , 0));
    		$this->view->setVar('openCity', $this->openCityList());
    		$this->view->pick("bp/bannerBpAdd");
    		return;
    	}
    	$response = new ResponseResult();
    	$response->callback = $req->getPost('callback', null, 'parent.setFormResult');
    	$response->callbackJavascriptTag = true;
    
    	$bp_id =  intval($req -> getPost('bp_id'));
    	$city = $req -> getPost('city');
    	$addr = $city;
    	$sort = intval($req -> getPost('sort',null,0));
    	$time = $req -> getPost('time');
    	// 判断空数据
    	if(empty($bp_id)) {
    		$response->sendError(ResponseResultStatus::PARAM_CANNOT_EMPTY, '参数异常！');
    		return $response;
    	}
    	//判断要推荐的美容是否存在
    	$bp = BeautyParlor::findFirst(" bp_id = $bp_id and bp_state = 1");
    	if(empty($bp)){
    		$response->sendError(ResponseResultStatus::BUSINESS, '当前推荐的美容院不存在或未发布或已删除！');
    		return $response;
    	}
    	//保存推荐美容院图片
    	$uploadFile = new UploadPic();
    	$uploadFile->request = $req;
    	$cover = $uploadFile ->beautyParlorCover();
    	 
    	if($cover == false || !is_array($cover) || count($cover) == 0 || $cover[0] == false) {
    		 
    		if($_FILES['bp_cover']['error'] == 1) {
    			$response->sendError(ResponseResultStatus::UPLOAD_FILE_ERROR, '文件大小超过了1M！');
    		}
    		return $response;
    	}
    
    	//判断美容院是否已经存在3个
    	/* if(CosPointBp::count("addr = $addr") >= 3){
    		$response->sendError(ResponseResultStatus::BUSINESS, '首页推荐美容院只能添加3个！');
    		return $response;
    	} */
    
    	//判断要添加的美容院是否已存在
    
    	/* if(CosPointBp::count('bp_id = ' . $bp_id.' and addr = '.$addr)){
    		$response->sendError(ResponseResultStatus::BUSINESS, '该美容院已经加入首页推荐！');
    		return $response;
    	}elseif(CosPointBp::count('sort = ' . $sort . ' and addr = '.$addr)){
    		$response->sendError(ResponseResultStatus::BUSINESS, '排序已经存在！');
    		return $response;
    	} */
    	if(CosPointBp::count('bp_id = ' . $bp_id.' and addr = '.$addr)){
    		$response->sendError(ResponseResultStatus::BUSINESS, '该美容院已经加入此城市推荐！');
    		return $response;
    	}
    	//实例化Model,组装数据
    	$cosPointBp = new CosPointBp();
    	$cosPointBp -> bp_id = $bp_id;
    	$cosPointBp -> addr = $addr;
    	$cosPointBp -> sort = $sort;
    	$cosPointBp -> img_url = $cover[0];
    	if($time!=''){
    		$timeArr=explode("至",$time);
    		$show_start_time = trim($timeArr[0]);
    		$show_end_time = trim($timeArr[1]);
    		$cosPointBp -> show_start_time=$show_start_time;
    		$cosPointBp -> show_end_time = $show_end_time;
    	}
    	//保存数据
    	if($cosPointBp->save() == false) {
    		$this->databaseErrorLog($cosPointBp);
    		$response->sendError(ResponseResultStatus::DATABASE_ERROR, '保存数据异常！');
    	} else {
    		$response->sendResult($cosPointBp->id);
    	}
    	return $response;
    }
    /**
     * 取消推荐美容院
     * @date: 2016-1-8 
     * @author: futao
     */
    public function calloffAction(){
    	$req=$this->request;
    	$id=$req->getQuery("id");
    	$cityid=$req->getQuery("city_id");
    	$flg=CosPointBp::find("id = $id")->delete();
    	if($flg==true){
    		echo "<script>window.parent.location.href='/manage/bp/bannerBp?City=$cityid'</script>";
    	}
    }
    
    
    
    
    
    
    
    
}